import React, { useImperativeHandle, forwardRef, useState } from 'react';
import { View, Text, StyleSheet, Modal, TextInput, TouchableOpacity, TouchableWithoutFeedback, ActivityIndicator } from 'react-native'
import { connect } from 'react-redux'
import { pTx } from "../utils/dimensions"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../realm"
import Realm from "realm"
import IconFont from '@pingtou/rn-vant-icons'
import LinearGradient from 'react-native-linear-gradient';
import httpApi from "../api"


const mapState = state => {
    return {
    }
}

const FriendRedPacketInApp = React.forwardRef((props, ref) => {
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const [open, setOpen] = useState(false)
    const [loading, setLoading] = useState(false)
    const [amount, setAmount] = useState(null)
    const [text, setText] = useState(null)
    const tokenTypeList = ['USDT', 'Tweet']
    const [tokenType, setTokenType] = useState(0)
    const sendFriendRedPacketInApp = async () => {
        if (!amount) return
        try {
            setLoading(true)
            const res = await httpApi.sendFriendRedPacketInApp({
                id: props.route.params.F,
                tokenType,
                amount
            })
            if (res.code == 20) {
                var timestamp = Date.parse(new Date()) / 1000
                const realmItem = {
                    F: props.route.params.F,
                    M: res.data.RedPacketId + " " + tokenType + " " + amount,
                    MT: 9,
                    S: -1,
                    RedPacketIdState: 0,
                    T: timestamp,
                    _id: new Realm.BSON.UUID(),
                    UserId: userInfo.Id,
                    RedPacketId: res.data.RedPacketId
                }
                realm.write(() => {
                    realm.create(schemaName.FriendMsgLis, realmItem, true);
                })
                setAmount(null)
                setOpen(false)
            }
            setLoading(false)

        } catch (error) {

        }
    }

    useImperativeHandle(ref, () => ({
        setOpen,
    }))


    return (
        <Modal
            visible={open}
            animationType="fade"
            onRequestClose={() => {
                setOpen(false)
            }}
        >
            <View style={styles.head}>
                <IconFont name="cross" style={styles.IconFont} />
                <Text style={styles.headText} onPress={() => setOpen(false)}>发红包</Text>
                <IconFont name="ellipsis" style={styles.IconFont} />
            </View>
            <View style={styles.centeredView}>

                <View style={styles.content}>
                    <View style={styles.cell}>
                        <Text style={styles.label}>货币类型</Text>
                        <TouchableOpacity onPress={() => setTokenType(tokenType ? 0 : 1)} style={styles.tokenType}>
                            <Text style={[styles.styleText]}>{tokenTypeList[tokenType]}</Text>
                            <IconFont name="arrow" style={styles.IconFont} />
                        </TouchableOpacity>
                    </View>
                    <View style={styles.cell}>
                        <Text style={styles.label}>单个金额</Text>
                        <TextInput
                            value={amount}
                            keyboardType="numeric"
                            style={[styles.amount, { textAlign: "right" }]}
                            placeholder="$0.00"
                            onChangeText={value => setAmount(Number(value).toString())}
                        />
                    </View>
                    <View style={styles.cell}>
                        <TextInput
                            value={text}
                            style={styles.amount}
                            maxLength={9}
                            placeholder="恭喜发财，大吉大利"
                            onChangeText={value => setText(value)}
                        />
                    </View>
                    <Text style={styles.amountPrice} ><Text style={{ fontSize: pTx(16) }}>$</Text>{amount || 0}</Text>
                    <View style={styles.RedPacketIncell}>
                        <TouchableWithoutFeedback disabled={loading} onPress={() => sendFriendRedPacketInApp()}>
                            <LinearGradient
                                colors={['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)']}
                                start={{ x: 0.25, y: 0.25 }}
                                end={{ x: 0.75, y: 0.75 }}
                                style={[styles.linearGradient]}>
                                <>
                                    {loading ? <ActivityIndicator /> : ""}
                                    <Text style={styles.RedPacketIn} >塞钱进红包</Text>
                                </>
                            </LinearGradient>
                        </TouchableWithoutFeedback>

                    </View>
                </View>
            </View>
        </Modal >
    );
})

export default connect(mapState, {}, null, { forwardRef: true })(FriendRedPacketInApp)

const styles = StyleSheet.create({
    centeredView: {
        flex: 1,
        paddingHorizontal: pTx(15),
        backgroundColor: "#EDEDED",
    },
    head: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(10),
        backgroundColor: "#EDEDED",
    },
    headText: {
        flex: 1,
        paddingVertical: pTx(5),
        fontSize: pTx(18),
        color: "#0A0C14",
        textAlign: "center"
    },
    headbutton: {
        paddingHorizontal: pTx(7),
        borderRadius: pTx(6),
        color: "#fff"
    },
    IconFont: {
        width: pTx(20),
        fontSize: pTx(18),
        color: "#000",
        fontWeight: "bold"
    },
    content: {
        paddingVertical: pTx(20),

    },
    cell: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
        height: pTx(53),
        marginBottom: pTx(12),
        paddingHorizontal: pTx(15),
        backgroundColor: "#fff",
        borderRadius: pTx(6),
    },
    label: {
        color: "#0A0C14",
        fontSize: pTx(16),
    },
    amount: {
        flex: 1,
        color: "#0A0C14",
        fontSize: pTx(16),
    },
    tokenType: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: "flex-end",
        alignItems: "center",
    },
    styleText: {
        marginLeft: pTx(16),
        color: "#0A0C14",
        fontSize: pTx(16),
        textAlign: "center",
        backgroundColor: "#fff",
    },
    amountPrice: {
        marginTop: pTx(15),
        textAlign: "center",
        color: "#0A0C14",
        fontSize: pTx(30),
    },
    RedPacketIncell: {
        marginTop: pTx(30),
        flexDirection: 'row',
        justifyContent: "center",
    },
    linearGradient: {
        borderRadius: pTx(6),
        paddingHorizontal: pTx(20),
        flexDirection: 'row',
        justifyContent: "center",
    },
    RedPacketIn: {
        paddingVertical: pTx(15),
        color: "#0A0C14",
        fontSize: pTx(16),
        fontWeight: "bold"
    }
})